package com.rrd.hive.udf;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
*
*@author liubaoxin
*@date 2019年11月21日
*/
public class InterestFeeUdf extends UDF {

    private Text res = new Text();
    private static Pattern pattern = Pattern.compile(",");
    private static Pattern pattern2 = Pattern.compile(":");
    private static Pattern pattern3 = Pattern.compile("#");

    public Double evaluate(String actFee,String dueFee ) {

   	 Map<String,Double> actMap = new HashMap<String,Double>();
        Map<String,Double> duMap = new HashMap<String,Double>();
        Set<String> actSet = new HashSet<String>();
        String arr[]=null;
        String arr2[]=null;
        if(actFee!=null && !actFee.equals("")){
        	arr=pattern.split(actFee);
        	for(String s: arr){
        		if(s.equals("")){
        			continue;
        		}
        		arr2=pattern2.split(s);
        		if(arr2.length!=2){
        		   continue;
        		}
        		actMap.put(arr2[0], Double.parseDouble(arr2[1]));
        		actSet.addAll(Arrays.asList(pattern3.split(arr2[0])));
        	} 
        }
        if(dueFee!=null && !dueFee.equals("")){
        	arr=pattern.split(dueFee);
        	for(String s: arr){
        		arr2=pattern2.split(s);
        		duMap.put(arr2[0], Double.parseDouble(arr2[1]));
        	} 
        }
        Iterator<String> it=duMap.keySet().iterator();
        String key="";
        Double d=0d;
        while(it.hasNext()){
        	key = it.next();
        	if(actSet.contains(key)){
        		duMap.put(key, 0d);
        	}else{
        		d=d+duMap.get(key);
        	}
        }
        it = actMap.keySet().iterator();
        while(it.hasNext()){
        	key = it.next();
        	d=d+actMap.get(key);
        }
   	 return d;
    }
    
    public static void main(String[] args) {
    	InterestFeeUdf ff = new InterestFeeUdf();
    	Double d=ff.evaluate(":0,,2019-08-02:55.77", "2019-09-02:36.3,2019-08-02:55.77,2019-07-12:0");
    	System.out.println(d);
    	
	}

}
